package com.rangers.manage.email.handler;

import java.io.File;
import java.util.Collections;
import java.util.Date;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.rangers.manage.email.domain.EmailDto;
import com.rangers.manage.email.domain.EmailServerType;
import com.rangers.manage.email.strategy.EmailStrategy;
import com.rangers.manage.email.strategy.TextStrategy;

@Component
public class EmailSendServiceImpl implements EmailSendService {

	
	private static final Logger log = LoggerFactory.getLogger(EmailSendServiceImpl.class);

	private final EmailServerProvider emailServerProvider;

	private final EmailSendTask emailSendTask;
	
	private EmailStrategy strategy;

	public EmailStrategy getStrategy() {
		return strategy;
	}

	public EmailSendServiceImpl(EmailServerProvider emailServerProvider,EmailSendTask emailSendTask) {
		super();
		this.emailServerProvider = emailServerProvider;
		this.emailSendTask = emailSendTask;
	}
	
	@Override
	public EmailSendServiceImpl setStrategy(EmailStrategy strategy) {
		this.strategy = strategy;
		return this;
	}

	@Override
	public void sendMail(EmailDto dto) throws MessagingException {
		log.info("邮件发送: start");
		EmailServerType serverType = dto.getServerType();
		Assert.notNull(serverType, "邮箱服务器的类型serverType不能为空");
		JavaMailSender mailSender = emailServerProvider.getByServerType(serverType.toString());
		Assert.notNull(mailSender, "邮箱服务器配置有误:未加载到配置信息");
		if (!StringUtils.hasText(dto.getSender())) {
			dto.setSender(emailServerProvider.getEmailConfig(serverType.toString()).getUsername());
		}
		MimeMessage mimeMessage = mailSender.createMimeMessage();
		// 第二个参数表示这个是mulipart类型的
		MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
		this.fillEmailMsg(helper, dto, !(this.strategy instanceof TextStrategy));

		// 显示是内置图片等:文件名与html的cid保持一致
		if (dto.getClassPathResource() != null && dto.getClassPathResource().length > 0) {
			for (ClassPathResource resource : dto.getClassPathResource()) {
				String fileName = resource.getFilename();
				helper.addInline(fileName.substring(0, fileName.lastIndexOf(".")), resource);
			}
		}
		// 附件
		if (dto.getAttachFile() != null && dto.getAttachFile().length > 0) {
			for (File file : dto.getAttachFile()) {
				FileSystemResource resource = new FileSystemResource(file);
				helper.addAttachment(file.getName(), resource);
			}
		}
		log.info("邮件发送：config->{},\nbody->{}", emailServerProvider.getEmailConfig(serverType.toString()), dto);
		EmailSendTask.addToQueue(Collections.singletonMap(mailSender, mimeMessage));
		emailSendTask.doSendTask();
	}

	private void fillEmailMsg(MimeMessageHelper helper, EmailDto dto, boolean isHtmlText) throws MessagingException {
		if (null != dto.getCc() && dto.getCc().length > 0) {
			helper.setCc(dto.getCc());
		}
		if (null != dto.getBcc() && dto.getBcc().length > 0) {
			helper.setBcc(dto.getBcc());
		}
		String[] receivers = dto.getReceivers();
		String subject = dto.getSubject();
		String sender = dto.getSender();
		Assert.hasText(sender, "邮件发送->发送方不能为空");
		Assert.isTrue(receivers != null && receivers.length > 0, "邮件发送->接收方不能为空");
		Assert.hasText(subject, "邮件发送->主题不能为空");
		String sendContent = this.sendContent(dto);
		Assert.hasText(sendContent, "邮件发送->发送内容不能为空");
		helper.setFrom(sender);
		helper.setTo(receivers);
		helper.setSubject(subject);
		helper.setSentDate(new Date());
		// true表示发送的是html消息
		helper.setText(sendContent, isHtmlText);
	}

	private String sendContent(EmailDto dto) {
		return this.strategy.getMsgContent(dto).toString();
	}

}
